/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListModel;
import com.sun.lwuit.list.ListCellRenderer;
import core.ScreenEngine;
import datamodel.Order;
import view.additional.OrderListRenderer;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class OrdersListForm extends BasicForm implements ActionListener
{
    private static final int LOOK_COMMAND_ID = 1;
    
    private final List items = new List();
    
//    private Order3 deletedOrder;
    
    private OrderForm orderForm;
    
    private String titleString; 
    private String orderTitleString;
    
    public OrdersListForm(String title, String orderTitleString)
    {
        this(title, orderTitleString, new OrderListRenderer());
    }
    
    public OrdersListForm(String title, String orderTitleString, ListCellRenderer renderer)
    {
        super(title);
          
        titleString = getTitle();
        this.orderTitleString = orderTitleString;
        
//        deletedOrder = new Order3(-1);
//        deletedOrder.setOrderShortDesc((new Label("order_deleted")).getText());
        
        init(renderer);        
    }
    
    private void init(ListCellRenderer renderer)
    {
        setLayout(new BorderLayout());
        setScrollable(false);
        
        items.setSelectCommandText("");
        items.setRenderer(renderer);
        items.setFixedSelection(List.FIXED_NONE_CYCLIC);
        //items.setSmoothScrolling(false);
        items.addActionListener(this);
        addComponent(BorderLayout.CENTER, items);
        
        //Команды на форме
        addCommand(new BackCommand());
        
        Command look = new Command("look", LOOK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                Order selected;
                synchronized(items)
                {
                    selected = (Order)items.getSelectedItem();
                }
                itemSelected(selected);
        
                evt.consume();
            }
        
        };
        addCommand(look);
    }
    
    public void setCountToTitle(int count)
    {
        setTitle(titleString + " " + count);
    }
    
    public void resetSelectedIndex()
    { 
        //Сбрасываем фокус
        items.setSelectedIndex(0);
    }
    
//    public void keyPressed(int keyCode)
//    {
//        int deletedIndex = -1;
//        //Если надо -удаляем удаленный заказ
//        int game = Display.getInstance().getGameAction(keyCode);
//        if(game == Display.GAME_DOWN || game == Display.GAME_UP) 
//        {
//            synchronized(items)
//            {
//                if (items.getSelectedItem() == deletedOrder)
//                {
//                    deletedIndex = items.getSelectedIndex();
//                }
//            }
//        }
//        
//        super.keyPressed(keyCode);
//        
//        if (deletedIndex != -1)
//        {
//            synchronized(items)
//            {
//                items.getModel().removeItem(deletedIndex);
//            }
//            
//            repaint();
//        }
//    }
    
    public void actionPerformed(ActionEvent evt)
    {
        Order selected;
        synchronized(items)
        {
            selected = (Order)items.getSelectedItem();
        }
        itemSelected(selected);
        
        evt.consume();
    }
    
    private void itemSelected(Order selected)
    {
        if (selected == null /*|| selected == deletedOrder*/)
        {
            return;
        }
        
        //ToDo Kvest
        if (orderForm == null)
        {
            orderForm = new OrderForm(orderTitleString);
        }
        
        //Устанавливаем заказ
        orderForm.setOrder(selected);
        
        //Отображаем форму
        ScreenEngine.getEngine().push(orderForm);
    }
    
    private Order getOrder(int index)
    {
        synchronized(items)
        {
            return (Order)items.getModel().getItemAt(index);
        }
    }
    
    public void clear()
    {
        synchronized(items)
        {
            ((DefaultListModel)items.getModel()).removeAll();
            items.setSelectedIndex(0);
        }
    }
    
    public void addOrderAfterOwn(Order order)
    {
        int index = 0;
        synchronized(items)
        {
            //Если есть - просто меняем
            for (int i = 0; i < items.size(); ++i)
            {
                if (getOrder(i).getOrderID() == order.getOrderID())
                {
                    ((DefaultListModel)items.getModel()).setItem(i, order);
                    index = -1;
                    break;
                }
                
                if (!getOrder(i).isAlien())
                {
                    index = i + 1;
                }
            }
            
            if (index != -1)
            {
                ((DefaultListModel)items.getModel()).addItemAtIndex(order, index);
            }
        }
    }
    
    public void addOrder(Order order, int index)
    {
        synchronized(items)
        {
            boolean found = false;
            //Если есть - просто меняем
            for (int i = 0; i < items.size(); ++i)
            {
                if (getOrder(i).getOrderID() == order.getOrderID())
                {
                    ((DefaultListModel)items.getModel()).setItem(i, order);
                    found = true;
                    break;
                }
            }
            
            if (!found)
            {
                ((DefaultListModel)items.getModel()).addItemAtIndex(order, index);
            }
        }
        
        //Перерисовываем
        repaint();
    }
    
    public void addOrder(Order order)
    {
        synchronized(items)
        {
            boolean found = false;
            //Если есть - просто меняем
            for (int i = 0; i < items.size(); ++i)
            {
                if (getOrder(i).getOrderID() == order.getOrderID())
                {
                    ((DefaultListModel)items.getModel()).setItem(i, order);
                    found = true;
                    break;
                }
            }
            
            if (!found)
            {
                items.getModel().addItem(order);
                //((DefaultListModel)items.getModel()).addItemAtIndex(order, 0);
            }
        }
        
        //Перерисовываем
        repaint();
    }
    
    public void removeOrder(Order order)
    {
        boolean needRepaint = false;
        synchronized(items)
        {
            for (int i = 0; i < items.size(); ++i)
            {
                if (getOrder(i).getOrderID() == order.getOrderID())
                {
                    //Проверяем, не выбранный ли это заказ
//                    if (items.getSelectedIndex() == i)
//                    {
//                        //Заменяем на удаленный заказ
//                        ((DefaultListModel)items.getModel()).setItem(i, deletedOrder);
//                    }
//                    else
//                    {
                        ((DefaultListModel)items.getModel()).removeItem(i);
//                    }
                    needRepaint = true;
                    break;
                }
            }
        }
        
        if (needRepaint)
        {
            repaint();
        }
    }
    
    public void replaceOrder(Order newOrder, Order oldOrder)
    {
        boolean needRepaint = false;
        synchronized(items)
        {
            //Если есть - просто меняем
            for (int i = 0; i < items.size(); ++i)
            {
                if (getOrder(i).getOrderID() == oldOrder.getOrderID())
                {
                    ((DefaultListModel)items.getModel()).setItem(i, newOrder);
                    needRepaint = true;
                    break;
                }
            }
        }
        
        if (needRepaint)
        {
            repaint();
        }
    }
}
